#!/usr/bin/perl

########################################################
# No point in running if there's no logged in user,
# or if it's a command-line invocation of installer
my $user = $ENV{USER};
exit 0 unless ($user);
exit 0 if ($ENV{COMMAND_LINE_INSTALL});

# We're running as root, so we do su $user -c $DISPLAYALERT
# to run with the localization preferences of the user that
# invoked the installation in the first place.

# Also, you can check for several apps by separating app 
# names with |, ie. "Keynote|Pages|Numbers"

########################################################
# settings
my $RUNNING_ERROR	= "Running";
my $OTHER_RUNNING_ERROR = "RunningOther";

my $APPLICATIONS = "Safari";

########################################################
# Find the Alert.app
my $PACKAGEDIR		= $ARGV[0];
my $DISPLAYALERT	= $PACKAGEDIR . "/Contents/Resources/Alert.app/Contents/MacOS/Alert";

if (!-e $DISPLAYALERT)
{
	# If it's not there, try the flat-file location.
	my $wd = `pwd`;
	chomp($wd);
	$DISPLAYALERT	= $wd . "/Tools/Alert.app/Contents/MacOS/Alert";
	
	# If it's not there, either, just give up.
	exit 0 unless (-e $DISPLAYALERT);
}

$DISPLAYALERT = "\"" . $DISPLAYALERT .  "\"";

########################################################
# If we have other_running_error defined, see if some other user is running app
if ( $OTHER_RUNNING_ERROR )
{
	my $otherIsRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep -v "^$user "`);
	while ($otherIsRunning)
	{
		$ENV{'ALERT_APP_ACTION'} = $OTHER_RUNNING_ERROR;
		system("/usr/bin/su", $user, "-c", $DISPLAYALERT);
		
		$otherIsRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep -v "^$user "`);
	}		
}

# Then see if we're running app
my $iAmRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep "^$user "`);
while ($iAmRunning) 
{
	$ENV{'ALERT_APP_ACTION'} = $RUNNING_ERROR;
	system("/usr/bin/su", $user, "-c", $DISPLAYALERT);
	
	$iAmRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep "^$user "`);
}

exit(0);
